//
//  UserInfo.m
//  FZAH
//
//  Created by Yoga on 2017/3/27.
//  Copyright © 2017年 zdqk. All rights reserved.
//

#import "UserInfo.h"

static UserInfo *_instance;

@implementation UserInfo

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    }) ;
    return _instance ;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _user = [[UserModel alloc] init];
    }
    return self;
}

- (void)getUserModel {
    
    UserModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getAccountSaveDocumentsPath]];
    if (model != nil) {
        self.user = model;
        self.isLogin = YES;
        
        NSLog(@"用户已登录");
        NSLog(@"token:%@", model.token);
    } else {
        self.isLogin = NO;
        NSLog(@"用户未登录");
    }
}

- (void)updateUserModel {
    // Encoding User 类要实现 NSCopying NSCoding 协议
    NSString *docFile  = [self getAccountSaveDocumentsPath];
    if([NSKeyedArchiver archiveRootObject:self.user toFile:docFile]) {
        NSLog(@"保存用户信息 Success");
    } else {
        NSLog(@"保存用户信息  Faile");
    }
}

- (void)logout {
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:[UserInfo shareInstance].user.mid.integerValue];
    
    self.user = nil;
//    self.userInterface = nil;
    self.isLogin = NO;
    
    [self updateUserModel];
}
- (void)updateDefaultAddress:(void (^)(BOOL))block {
    
    [MYAFNetworking POST:URL_Get_Address parameters:@{@"pageSize":@"1000",@"pageNumber":@1} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *dics = responseObject;
                // 数据列表
                NSArray *arr = dics[@"data"];
                for (NSDictionary *dataDic in arr) {
                    AddressModel *model = [AddressModel mj_objectWithKeyValues:dataDic];
                    if (model.isdefault) {
                        self.user.defaultAddress = model;
                        break;
                    }
                    if ([model isEqual:[arr lastObject]] && !self.user.defaultAddress) {
                        self.user.defaultAddress = [arr firstObject];
                    }
                }
                
                [self updateUserModel];
                block(YES);
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(NO);
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(NO);
        });
    }];
    
}

- (void)updateUserInterfaceModel:(void (^)(BOOL success))block {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [MYAFNetworking POST:URL_Get_Member_Info parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = responseDic[@"code"];
        if (code && [code isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *data = responseDic[@"data"];
                UserInterfaceModel *model = [UserInterfaceModel mj_objectWithKeyValues:data];
                self.user.mid = model.mid;
                self.user.mimg = model.mimg;
                self.user.mname = model.mname;
                self.user.mnickname = model.mnickname;
                self.user.msex = model.msex;
                self.user.mtel = model.mtel;
                self.user.mbirthday = model.mbirthday;
                self.user.misreceive = model.misreceive;
                
                self.user.minvitationcode = model.minvitationcode;
                self.user.fmid = model.fmid;
                self.user.fmname = model.fmname;
                self.user.createtime = model.createtime;
                self.user.ispaypass = model.ispaypass;
                self.user.mstatus = model.mstatus;
                self.user.remark = model.remark;
                
                self.user.aid = model.aid;
                self.user.aname = model.aname;
                self.user.cid = model.cid;
                self.user.cname = model.cname;
                self.user.pid = model.pid;
                self.user.pname = model.pname;
                
                [self updateUserModel];
                [self updateDefaultAddress:^(BOOL success) {
                    if (success) {
                        block(YES);
                    } else {
                        block(NO);
                    }
                }];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(NO);
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(NO);
        });
    }];
}
- (void)updateUserCounterFeeModel:(void (^)(BOOL success))block {
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    [MYAFNetworking POST:URL_Get_Counter_Fee parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSDictionary *responseDic = responseObject;
//        NSString *code = [responseDic safeStringForKey:@"code"];
//        if (code && [code isEqualToString:@"200"]) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
//                UserCounterFeeModel *model = [UserCounterFeeModel mj_objectWithKeyValues:data];
//                self.userCounterFee = model;
//                block(YES);
//            });
//        } else {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                block(NO);
//            });
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            block(NO);
//        });
//    }];
}
// 路径
- (NSString*)getDocumentDirectory {
    NSArray *paths =
    NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return  [paths objectAtIndex:0];
}

- (NSString*)getAccountSaveDocumentsPath {
    NSString *userSavePath = [[self getDocumentDirectory] stringByAppendingPathComponent:@"account.data"];
    return userSavePath;
}

- (NSString*)getDrviceUUIDSaveDocumentsPath {
    NSString *drviceUUIDSavePath = [[self getDocumentDirectory] stringByAppendingPathComponent:@"drviceUUID.data"];
    return drviceUUIDSavePath;
}

- (void)saveLatitudeLongitudeTimeStap {
    NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [[NSUserDefaults standardUserDefaults] setDouble:time forKey:@"LatitudeLongitudeTimeStap"];
}

- (NSTimeInterval)getLatitudeLogitudeTimeStap {
    NSTimeInterval time = [[NSUserDefaults standardUserDefaults] doubleForKey:@"LatitudeLongitudeTimeStap"];
    return time;
}


- (BOOL)isFirstLaunchApp {
//    return YES;
    return ![[[NSUserDefaults standardUserDefaults] objectForKey:@"launchGuideView"] isEqualToString:@"1"];
}

- (void)didLoadGuideView {
//    return;
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"launchGuideView"];
}

@end
